<template>
  <view>
    <view class="search-box">
      <uni-search-bar @input="input" :radius="100" cancelButton="none"></uni-search-bar>
    </view>
    <view class="searchList" v-if="(serachResults.length!==0 || kw!='')?true:false">
      <view class="search-item" v-for="(item,index) in serachResults" :key="index" @click="gotoGoodsDetail(item)">
        <view class="goods_name">{{item.goods_name}}</view>
        <uni-icons type="arrowright"></uni-icons>
      </view>
    </view>

    <view class="historyArea" v-else>
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash" @click="deth"></uni-icons>
      </view>
      <view class="historyList">
        <uni-tag class="history-item" :text="item" v-for="(item,index) in historys" :key="index"
          @click="gotoGoodsList(item)"></uni-tag>
      </view>
    </view>


  </view>
</template>

<script>
  export default {
    data() {
      return {
        // 延时器的 timerId
        timer: null,
        // 搜索关键词
        kw: '',
        serachResults: [],
        historyList: ['昨天', '今天', '明天']
      };
    },
    onLoad() {
      this.historyList = JSON.parse(uni.getStorageSync('kw') || '[]')
    },
    computed: {
      historys() {
        // 注意：由于数组是引用类型，所以不要直接基于原数组调用 reverse 方法，以免修改原数组中元素的顺序
        // 而是应该新建一个内存无关的数组，再进行 reverse 反转
        return [...this.historyList].reverse()
      }
    },
    methods: {
      input(e) {
        // 清除 timer 对应的延时器
        clearTimeout(this.timer)
        // 重新启动一个延时器，并把 timerId 赋值给 this.timer
        this.timer = setTimeout(() => {
          // 如果 500 毫秒内，没有触发新的输入事件，则为搜索关键词赋值
          this.kw = e
          this.getSearchResults()
          console.log(this.kw)
        }, 500)
      },
      async getSearchResults() {
        if (this.kw === '') {
          this.searchResults = []
          return
        }
        const {
          data: res
        } = await uni.$http.get('/api/public/v1/goods/qsearch?query=' + this.kw)
        console.log(res)
        this.serachResults = res.message
        this.saveSerchHistory()
      },
      gotoGoodsDetail(item) {
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?goods_id=' + item.goods_id
        })
      },
      saveSerchHistory() {
        // this.historyList.push(this.kw)
        const set = new Set(this.historyList)
        set.delete(this.kw)
        set.add(this.kw)
        this.historyList = Array.from(set)
        // 调用 uni.setStorageSync(key, value) 将搜索历史记录持久化存储到本地
        uni.setStorageSync('kw', JSON.stringify(this.historyList))
      },
      deth() {
        uni.showModal({
          title: '删除吗',
          content: '要留清白在人间~~~',
          success: (res) => {

            if (res.confirm) {
              this.historyList = []
              uni.setStorageSync('kw', '[]')
            } else if (res.cancel) {
              console.log('犹豫就会败北');
            }
          }
        })


      },
      gotoGoodsList(kw) {
        uni.navigateTo({
          url: '/subpkg/goods_list/goods_list?query=' + kw
        })
      }
    }

  }
</script>

<style lang="scss">
  .uni-searchbar {
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    flex-direction: row;
    position: relative;
    padding: 16rpx;
    /* 将默认的 #FFFFFF 改为 #C00000 */
    background-color: #c00000;
  }

  .search-box {
    position: sticky;
    top: 0;
    z-index: 999;
  }

  .searchList {
    padding: 0 5px;

    .search-item {
      display: flex;
      font-size: 14px;
      align-items: center;
      justify-content: space-between;
      border-bottom: 1px solid #efefef;
      padding: 13px 0;

      .goods_name {
        // 文字不允许换行（单行文本）
        white-space: nowrap;
        // 溢出部分隐藏
        overflow: hidden;
        // 文本溢出后，使用 ... 代替
        text-overflow: ellipsis;
        margin-right: 3px;
      }
    }
  }

  .historyArea {
    padding: 0 5px;

    .history-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 40px;
      font-size: 13px;
      border-bottom: 1px solid #efefef;
    }

    .historyList {
      display: flex;
      flex-wrap: wrap;

      .history-item {
        margin-right: 5px;
        margin-top: 5px;
      }
    }
  }
</style>
